﻿/**
<code>
  <author name="Zealic" email="zealic(at)gmail.com" type="Creator"/>
</code>
**/
using System;
using System.Collections.Generic;


namespace Zealib.Transform
{
    /// <summary>
    /// Transform global management.
    /// </summary>
    public static class TransformManager
    {
        private static readonly IList<ITransformerFactory> s_Factories = new List<ITransformerFactory>();

        static TransformManager()
        {
            RegisterFactory(new TypeConverterTransformerFactory());
        }

        /// <summary>
        /// Create a transformer.
        /// </summary>
        /// <param name="sourceType">Source type.</typeparam>
        /// <returns>created transformer.</returns>
        public static ITransformer GetTransformer(Type sourceType)
        {
            foreach (ITransformerFactory factory in s_Factories)
            {
                ITransformer transformer;
                if (factory.TryCreate(sourceType, out transformer))
                    return transformer;
            }
            throw new NotSupportedException();
        }

        /// <summary>
        /// Register transformer factory.
        /// </summary>
        /// <param name="factory">Transformer factory.</param>
        public static void RegisterFactory(ITransformerFactory factory)
        {
            if (factory == null) throw new ArgumentNullException("factory");
            s_Factories.Insert(0, factory);
        }

        /// <summary>
        /// Unregister transformer factory.
        /// </summary>
        /// <param name="factory">Transformer factory.</param>
        public static bool UnregisterFactory(ITransformerFactory factory)
        {
            if (factory == null) throw new ArgumentNullException("factory");
            if (s_Factories.Contains(factory))
            {
                s_Factories.Remove(factory);
                return true;
            }
            return false;
        }

    }
}
